import React, { useState, useEffect } from 'react';
import { Upload, message,  Modal, Progress } from 'antd';
import { InboxOutlined } from '@ant-design/icons';
import type { UploadFile } from 'antd/es/upload/interface';
import styles from './index.module.less';
import clsx from 'clsx';
import { useAnalysisStore } from '@/stores/analysisStore';

const { Dragger } = Upload;

const AddPhoto: React.FC = () => {
  const [previewOpen, setPreviewOpen] = useState(false);
  const [progress, setProgress] = useState(0);
  const [showProgress, setShowProgress] = useState(false);
  const { analysisResult, setAnalysisResult } = useAnalysisStore();
  

  const handlePreview = async (file: UploadFile) => {
    const preview = await getBase64(file.originFileObj as File);
    setAnalysisResult({
      ...analysisResult,
      previewImage: preview
    });
  };

  const getBase64 = (file: File): Promise<string> =>
    new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result as string);
      reader.onerror = (error) => reject(error);
    });

  const handleChange = (info: any) => {
    const { file, fileList } = info;
    
    setAnalysisResult({
      ...analysisResult,
      uploadedFileList: fileList
    });
    
    if (file.status === 'uploading') {
      return;
    } else if (file.status === 'done') {
      handlePreview(file);
      setShowProgress(true);
      setProgress(0);
      
      // 模拟进度增加
      const timer = setInterval(() => {
        setProgress(prev => {
          if (prev >= 100) {
            clearInterval(timer);
            return 100;
          }
          return prev + 2; // 每100ms增加2%
        });
      }, 100);

      // 模拟请求获取html和md字符串
      setTimeout(() => {
        const result = {
          html: `
            <!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>精益之星-度量平台</title>
    <style>
        body {
            margin: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji';
            background-color: #f4f7fa;
            color: #333;
        }

        /* Header */
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 50px;
            background-color: #0a1c38;
            color: #fff;
            height: 64px;
        }

        .header .logo {
            font-size: 20px;
            font-weight: bold;
        }

        .header .logo-icon {
            color: #4a90e2;
            margin-right: 10px;
        }

        .header nav ul {
            margin: 0;
            padding: 0;
            list-style: none;
            display: flex;
        }

        .header nav li {
            margin: 0 20px;
        }

        .header nav a {
            color: #c0c8d3;
            text-decoration: none;
            font-size: 15px;
            padding: 20px 0;
            position: relative;
        }
        
        .header nav a.active,
        .header nav a:hover {
            color: #fff;
        }

        .header nav a.active::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 3px;
            background-color: #4a90e2;
        }

        .header .user-section {
            display: flex;
            align-items: center;
        }

        .header .user-actions {
            display: flex;
            align-items: center;
            gap: 25px;
            margin-right: 20px;
        }
        
        .header .user-action {
            display: flex;
            flex-direction: column;
            align-items: center;
            cursor: pointer;
            font-size: 12px;
            color: #c0c8d3;
        }
        
        .header .user-action .icon {
            font-size: 20px;
            margin-bottom: 4px;
        }

        .header .update-btn {
            background-color: #34c759;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 6px 12px;
            font-size: 12px;
            cursor: pointer;
            margin-left: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }

        /* Hero Section */
        .hero {
            background-color: #0b1a33;
            background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><text x="0" y="50" font-family="monospace" font-size="12" fill="rgba(255,255,255,0.1)">010101</text></svg>');
            height: 300px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            color: white;
            text-align: center;
        }
        .hero h1 {
            font-size: 48px;
            margin: 0;
            font-weight: 500;
        }
        .hero p {
            font-size: 18px;
            color: #c0c8d3;
            margin-top: 20px;
            position: relative;
        }
        .hero p::after {
            content: '';
            position: absolute;
            bottom: -15px;
            left: 50%;
            transform: translateX(-50%);
            width: 50px;
            height: 2px;
            background-color: #666;
        }

        /* Main Content */
        .main-content {
            padding: 50px;
            background-color: #fff;
        }
        .nav-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 20px;
            max-width: 1400px;
            margin: auto;
        }

        /* Card styles */
        .card {
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 25px;
            display: flex;
            flex-direction: column;
            box-shadow: 0 1px 3px rgba(0,0,0,0.05);
        }

        .card.highlighted {
            background-color: #007bff;
            color: white;
            border-color: #007bff;
        }

        .card-header {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }
        .card-icon {
            font-size: 32px;
            margin-right: 15px;
            color: #007bff;
        }
        .card.highlighted .card-icon {
            color: white;
        }
        .card-title {
            font-size: 18px;
            font-weight: 600;
        }
        .card.highlighted .card-title {
            color: white;
        }

        .card-body ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        .card-body li {
            margin-bottom: 12px;
        }
        .card-body a {
            text-decoration: none;
            color: #555;
            font-size: 14px;
        }
        .card-body a:hover {
            color: #007bff;
        }
        .card.highlighted a {
            color: #e0eaff;
        }
        .card.highlighted a:hover {
            color: #fff;
        }
    </style>
</head>
<body>

    <header class="header">
        <div class="logo">
            <span class="logo-icon">Ⓜ</span>精益之星-度量平台
        </div>
        <nav>
            <ul>
                <li><a href="#" class="active">首页</a></li>
                <li><a href="#">组织级度量 ▾</a></li>
                <li><a href="#">成效分析与衡量 ▾</a></li>
                <li><a href="#">重点专项度量 ▾</a></li>
                <li><a href="#">度量仪表盘 ▾</a></li>
                <li><a href="#">项目/迭代度量 ▾</a></li>
                <li><a href="#">数据服务 ▾</a></li>
                <li><a href="#">我的报表</a></li>
            </ul>
        </nav>
        <div class="user-section">
            <div class="user-actions">
                <div class="user-action"><span class="icon">📱</span>扫码进群</div>
                <div class="user-action"><span class="icon">💬</span>反馈</div>
                <div class="user-action"><span class="icon">❓</span>帮助</div>
                <div class="user-action"><span class="icon">👤</span>梁乐达</div>
            </div>
            <button class="update-btn">今日数据已更新</button>
        </div>
    </header>

    <section class="hero">
        <h1>网站导航</h1>
        <p>提供专业、便捷、全面、高时效、可信赖的数据服务</p>
    </section>

    <main class="main-content">
        <div class="nav-grid">
            <div class="card">
                <div class="card-header">
                    <div class="card-icon">🏠</div>
                    <h3 class="card-title">组织级度量</h3>
                </div>
                <div class="card-body">
                    <ul>
                        <li><a href="#">全景度量指标</a></li>
                        <li><a href="#">关键指标大屏</a></li>
                        <li><a href="#">资源投入情况</a></li>
                        <li><a href="#">工程技术度量</a></li>
                        <li><a href="#">团队画像</a></li>
                    </ul>
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <div class="card-icon">📊</div>
                    <h3 class="card-title">成效分析与衡量</h3>
                </div>
                <div class="card-body">
                    <ul>
                        <li><a href="#">成效分析仪表盘 (IB)</a></li>
                        <li><a href="#">领域级成效分析</a></li>
                        <li><a href="#">产品级成效分析</a></li>
                    </ul>
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <div class="card-icon">🏢</div>
                    <h3 class="card-title">重点专项度量</h3>
                </div>
                <div class="card-body">
                    <ul>
                        <li><a href="#">应用运维质量度量</a></li>
                        <li><a href="#">投产有效性</a></li>
                        <li><a href="#">紧急&特急发布</a></li>
                        <li><a href="#">研发安全度量</a></li>
                    </ul>
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <div class="card-icon">⚙️</div>
                    <h3 class="card-title">度量仪表盘</h3>
                </div>
                <div class="card-body">
                    <ul>
                        <li><a href="#">四大研发中心</a></li>
                        <li><a href="#">测试中心</a></li>
                        <li><a href="#">云数据中心</a></li>
                        <li><a href="#">架构管理团队</a></li>
                        <li><a href="#">理财研发中心</a></li>
                        <li><a href="#">信用卡中心</a></li>
                        <li><a href="#">招银云创</a></li>
                    </ul>
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <div class="card-icon">📚</div>
                    <h3 class="card-title">项目/迭代度量</h3>
                </div>
                <div class="card-body">
                    <ul>
                        <li><a href="#">项目级度量</a></li>
                        <li><a href="#">敏捷迭代度量</a></li>
                    </ul>
                </div>
            </div>

            <div class="card highlighted">
                <div class="card-header">
                    <div class="card-icon">📈</div>
                    <h3 class="card-title">数据服务</h3>
                </div>
                <div class="card-body">
                    <ul>
                        <li><a href="#">自助分析</a></li>
                        <li><a href="#">自助查询</a></li>
                        <li><a href="#">度量报告</a></li>
                        <li><a href="#">API接口</a></li>
                        <li><a href="#">数据配置</a></li>
                    </ul>
                </div>
            </div>

            <div class="card">
                <div class="card-header">
                    <div class="card-icon">📄</div>
                    <h3 class="card-title">我的报表</h3>
                </div>
                <div class="card-body">
                    <ul>
                        <li><a href="#">我的报表</a></li>
                    </ul>
                </div>
            </div>
        </div>
    </main>

</body>
</html>
          `,
          markdown: `
# 生成的Markdown文档

## 页面结构
- 头部区域
- 内容区域
- 底部区域

## 响应式设计
- 移动端适配
- 平板适配
- 桌面端适配

## 组件说明
1. 导航栏
2. 内容区
3. 页脚
          `
        };
        setAnalysisResult({
          ...result,
          uploadedFileList: fileList,
          hasUploadedFile: true
        });
        setShowProgress(false);
        message.success(`${file.name} 上传成功`);
      }, 5000);
    } else if(file.status === 'removed'){
      setAnalysisResult({
        html: '',
        markdown: '',
        uploadedFileList: [],
        previewImage: '',
        hasUploadedFile: false
      });
      setShowProgress(false);
    } else if (file.status === 'error') {
      message.error(`${file.name} 上传失败`);
      setShowProgress(false);
    }
  };

  const customRequest = ({ file, onSuccess, }: any) => {
    // 验证文件类型
    const isImage = file.type.startsWith('image/');
    console.log(file,"相应的文件")
    if (!isImage) {
      message.error('只能上传图片文件！');
      return;
    }

    // 验证文件大小
    const isLt5M = file.size / 1024 / 1024 < 10;
    if (!isLt5M) {
      message.error('图片大小不能超过 10MB！');
      return;
    }

    // 模拟上传成功
    setTimeout(() => {
      onSuccess('ok');
    }, 0);
  };

  //处理antpro图片上传清晰度不够问题
  const preFunc = async (file: File | Blob): Promise<string> => {
    if (file instanceof File) {
      return await getBase64(file);
    }
    return '';
  };


  return (
    <div className={clsx(styles.uploadContainer,{
      [styles.hasImage]: (analysisResult?.uploadedFileList || []).length > 0
    })}>
      <Dragger
        className={styles.dragger}
        name="file"
        multiple={false}
        accept=".jpg,.jpeg,.png"
        onChange={handleChange}
        onPreview={()=>{setPreviewOpen(true)}}
        fileList={analysisResult?.uploadedFileList}
        customRequest={customRequest}
        listType="picture-card"
        maxCount={1}
        previewFile={preFunc}
      >
        <p className={styles.uploadIcon}>
          <InboxOutlined />
        </p>
        <p className={styles.uploadText}>点击或拖拽文件到此区域上传</p>
        <p className={styles.uploadHint}>
          支持单个或批量上传，仅支持 jpg/png/webp 格式,最大10MB
        </p>
      </Dragger>

      {showProgress && (
        <div className={styles.progressContainer}>
          <Progress type="circle" percent={progress} />
        </div>
      )}

      <Modal
        open={previewOpen}
        footer={null}
        onCancel={() => setPreviewOpen(false)}
        width="80%"
        style={{ top: '5vh', bottom: '5vh' }}
      >
        <img
          alt="预览图片"
          src={analysisResult?.previewImage}
        />
      </Modal>
    </div>
  );
};

export default AddPhoto; 